package com.stlm2.controller;

import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.service.*;
import com.stlm2.dems.user.entity.Login;
import com.stlm2.dems.user.entity.UserState;
import com.stlm2.util.Convert;
import com.stlm2.util.ExcelUtils;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;
import net.sf.json.JSONArray;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.Collections;

/**
 * Created by sfy on 2017/10/24.
 */
@Controller
@RequestMapping("/purchaseOrderC")
public class PurchaseOrderController {

    @Resource
    private Memcached memcached;
    @Resource
    private PurchaseOrderService purchaseOrderService;
    @Resource
    private GoodSpecificationDao goodSpecificationDao;
    @Resource
    private DdmShopDao ddmShopDao;
    @Resource
    private ShopOrderService shopOrderService;
    @Resource
    private GoodsOrderDao goodsOrderDao;
    @Resource
    private GoodSpecificationDao getGoodSpecificationDao;
    @Resource
    private DdmGoodsDao ddmGoodsDao;
    @Resource
    private UserService userService;
    @Resource
    private MessagesDao messagesDao;



    /**
     * 后台订单  shopOrder 查询
     * 2017-11-11 16:32:45
     * ffl
     * @param token
     * @param shopId 店铺或仓库id
     * @param userName 用户账号 手机号
     * @param realName 用户姓名
     * @param payTypeValue 支付方式 1网上支付 2到店支付 3银行转账 4分期付款
     * @param deliveryTypeValue 配送方式 1到店自取 2送货上门
     * @param orderStateValue 订单状态值 1创建订单 2已取消 3已支付 4待发货 5已发货 6已完成 7已退款 10确认收货 11驳回订单 12退款申请 13放弃购买
     * @param purchaseOrderCode 购买订单编码
     * @param code 订单编码
     * @param wayBillNum 物流单号
     * @param pageNum 查询页数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/search.json",produces = "application/json;charset=utf-8")
    public String search(String token,String shopId,String userName,String realName,String payTypeValue,String deliveryTypeValue,String orderStateValue, String purchaseOrderCode ,String code,String wayBillNum,String pageNum) {
        return shopOrderService.search(token, shopId, userName, realName, payTypeValue, deliveryTypeValue, orderStateValue, purchaseOrderCode, code, wayBillNum, pageNum);
    }


    @RequestMapping("/export.json")
    public void export(HttpServletResponse response, String orderStateValue, String exportTimeStr, String exportTimeEnd, String shopId) {
        ShopOrder param = new ShopOrder();

        List<String[]> data = new ArrayList<String[]>();
        String[] fieldName = new String[]{"序号", "商品编号", "订单编号", "发件人", "宝贝", "供货价", "省市", "详细地址", "手机", "姓名", "价格", "备注", "快递名称", "快递单号", "订单状态", "状态生成时间"};

        String excelName = "订单导出表";

        Date exportStartTime = null;
        Date exportEndTime = null;
        if (!StringUtils.isEmpty(exportTimeStr)) //查询订单相关日期
            exportStartTime = Convert.toCalendar(exportTimeStr).getTime();
        if(!StringUtils.isEmpty(exportTimeEnd))
            exportEndTime=Convert.toCalendar(exportTimeEnd).getTime();

        OrderState orderState = null;
        if (NumberUtils.isDigits(orderStateValue)) {//查询的订单状态
            orderState = OrderState.getByIntValue(NumberUtils.toInt(orderStateValue));
        }
        param.setOrderState(orderState);

        if (NumberUtils.isDigits(shopId)) //根据供应商查询
            param.setShopId(NumberUtils.toInt(shopId));

        //默认导出的订单为送货上门的订单，因为到店自取的订单没有物流单号，无法再导入。
        param.setDeliveryType(DeliveryType.Delivery);

        if (exportStartTime == null || exportEndTime == null || exportEndTime.getTime() <= exportStartTime.getTime() || orderState == null) {
            ExcelUtils.makeStreamExcel(excelName, excelName, fieldName, data, null, response);  // 调用Excel工具类，生成Excel文件
            return;
        }

        if (OrderState.Create.equals(orderState)) {
            param.setCreateStartTimeExport(exportStartTime);
            param.setCreateEndTimeExport(exportEndTime);
        } else if (OrderState.Cancel.equals(orderState)) {
            param.setCancleStartTimeExport(exportStartTime);
            param.setCancleEndTimeExport(exportEndTime);
        } else if (OrderState.Payment.equals(orderState)) {
            param.setPayStartTimeExport(exportStartTime);
            param.setPayEndTimeExport(exportEndTime);
        } else if (OrderState.Reject.equals(orderState)) {//驳回订单
            param.setHandleStartTimeExport(exportStartTime);
            param.setHandleEndTimeExport(exportEndTime);
        } else if (OrderState.StopBuying.equals(orderState)) {//放弃购买
            param.setHandleStartTimeExport(exportStartTime);
            param.setHandleEndTimeExport(exportEndTime);
        } else if (OrderState.Delivery.equals(orderState)) {//待发货订单
            param.setHandleStartTimeExport(exportStartTime);
            param.setHandleEndTimeExport(exportEndTime);
        } else if (OrderState.Deliveried.equals(orderState)) {
            param.setDeliveStartTimeExport(exportStartTime);
            param.setDeliveEndTimeExport(exportEndTime);
        } else if (OrderState.Receipt.equals(orderState)) {
            param.setReceiptStartTimeExport(exportStartTime);
            param.setReceiptEndTimeExport(exportEndTime);
        } else {
            ExcelUtils.makeStreamExcel(excelName, excelName, fieldName, data, null, response);  // 调用Excel工具类，生成Excel文件
            return;
        }

        excelName = "订单导出表_" + orderState.toString() + "_" + Convert.toShortYMD(exportStartTime)+"至"+Convert.toShortYMD(exportEndTime);

        List<ShopOrder> orderList = shopOrderService.getList(-1, Integer.MAX_VALUE, param);

        //  将查询结果数据组装成一个List<String[]>数组
        for (ShopOrder order : orderList) {
            //已支付订单变成待发货，其它订单不做处理
            if(order.getOrderState().equals(OrderState.Payment)){
                Boolean result = shopOrderService.handleOrder(order, OrderState.Delivery, "导入批量待发货", getCurrentUser());
                System.out.println("导入待发货结果：" + result);
            }

            DdmShop merchant = ddmShopDao.getById(order.getShopId());
            String sendPerson = "";
            if (merchant == null) {
                sendPerson = "叮当网商城";
            } else {
                sendPerson = merchant.getName();
            }

            GoodsOrder itemParam = new GoodsOrder();
            itemParam.setShopOrderCode(order.getCode());
            List<GoodsOrder> itemsList = goodsOrderDao.queryList(-1, -1, itemParam);
            String goodsSupplyPrice = "";
            String no = null;
            BigDecimal supplyPrice = new BigDecimal(0);
            List<String> goodsNameList = new ArrayList<String>();
            //保存商品数量与名称
            List<String> goodsList = new ArrayList<String>();
            for (GoodsOrder items : itemsList) {
                StringBuffer goodsNameStringBuffer = new StringBuffer();
                String specification = "";
                if (!StringUtils.isEmpty(items.getGoodsSpecificationId())) {
                    GoodSpecification goodSpecification = goodSpecificationDao.getById(items.getGoodsSpecificationId());
                    specification = goodSpecification.getPropertiesName();
                }

                /*新增导出订单编号 + 规格编号  2016年9月18日 11:33:07  付春雨*/
                DdmGoods goods = ddmGoodsDao.getById(items.getGoodsId());
                no = StringUtils.isEmpty(goods.getCode()) ? "" : goods.getCode().trim();

                goodsNameStringBuffer.append("【" + no + "】");

                goodsNameStringBuffer.append("【" + (StringUtils.isEmpty(items.getGoodsName()) ? "" : items.getGoodsName()) + "】");


                if (!StringUtils.isEmpty(specification)) {
                    goodsNameStringBuffer.append("【" + specification + "】");
                }
                goodsNameStringBuffer.append("【" + items.getNum() + "件】");
                goodsSupplyPrice = goodsSupplyPrice + items.getSalePrice().toString()+ "*" + items.getNum();
                supplyPrice=supplyPrice.add(items.getSalePrice().multiply(new BigDecimal(items.getNum())));
                //添加到数据，使用#分割
                String shortNameCount = ( items.getGoodsName() + "#" + items.getNum());
                goodsList.add(shortNameCount);
                goodsNameList.add(goodsNameStringBuffer.toString());
            }
            //goodsNameList排序,换行
            Collections.sort(goodsNameList);
            StringBuffer goodsNameStrings = new StringBuffer();
            for (int i = 0; i < goodsNameList.size(); i++) {
                goodsNameStrings.append(goodsNameList.get(i));
                goodsNameStrings.append("\n");
            }
            goodsSupplyPrice = goodsSupplyPrice + "=" +  supplyPrice.toString();

            PurchaseOrder purchaseOrder = purchaseOrderService.getByCode(order.getPurchaseOrderCode());
            String provinceName = purchaseOrder.getCity();
            String cityName = purchaseOrder.getAddressDetail();

            Date generationTime = null;
            if (OrderState.Create.equals(order.getOrderState())) {
                generationTime = order.getCreateTime();
            } else if (OrderState.Cancel.equals(order.getOrderState())) {
                generationTime = order.getCancelTime();
            } else if (OrderState.Payment.equals(order.getOrderState())) {
                generationTime = order.getPayTime();
            } else if (OrderState.Reject.equals(order.getOrderState())) {//驳回订单
                generationTime = order.getHandleTime();
            } else if (OrderState.Delivery.equals(order.getOrderState())) {//待发货订单
                generationTime = order.getHandleTime();
            } else if (OrderState.Deliveried.equals(order.getOrderState())) {
                generationTime = order.getDeliverTime();
            } else if (OrderState.Receipt.equals(order.getOrderState())) {
                generationTime = order.getReceiptTime();
            }
            String generationTimeStr = generationTime != null ? Convert.toFullYMDHMS(generationTime) : "";
            String[] row = new String[]{String.valueOf(order.getId()), no, order.getCode(), sendPerson,
                    goodsNameStrings.toString(), goodsSupplyPrice, provinceName, cityName, purchaseOrder.getPhone(), purchaseOrder.getName(),
                    order.getTotalMoney().toString(), order.getRemark() != null ? order.getRemark() : "", "", "", order.getOrderState().toString(), generationTimeStr};
            data.add(row);
        }
        ExcelUtils.makeStreamExcel(excelName, excelName, fieldName, data, null, response);  // 调用Excel工具类，生成Excel文件
    }
    @ResponseBody
    @RequestMapping(value = "/import.json",produces = "application/json;charset=utf-8")
    public String importExpress(@RequestParam("file") MultipartFile file) throws IOException {
        Workbook book = new HSSFWorkbook(file.getInputStream());
        Sheet sheet = book.getSheetAt(0);
        if (sheet.getLastRowNum() >= 1) {
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                String idStr = ExcelUtils.getCellData(row.getCell(0));
                ShopOrder order = shopOrderService.findEntityById(NumberUtils.toInt(idStr));
                if (order == null)
                    return CodeContent.returnFailure("序号" + idStr + "订单不存在!");

                String expressStr = ExcelUtils.getCellData(row.getCell(12));
                ExpressType expressType = ExpressType.getByName(org.apache.commons.lang.StringUtils.trim(expressStr));
                if (expressType==null)
                    return CodeContent.returnFailure("序号" + idStr + "订单快递公司有误（空或输入错误）" + order.getOrderState().toString() + "!");

                String expressCodeStr = ExcelUtils.getCellData(row.getCell(13));
                if (org.apache.commons.lang.StringUtils.isBlank(org.apache.commons.lang.StringUtils.trim(expressStr)))
                    return CodeContent.returnFailure("序号" + idStr + "订单快递单号为空!");

                if (!OrderState.Delivery.equals(order.getOrderState()))
                    return CodeContent.returnFailure("序号" + idStr + "订单状态为" + order.getOrderState().toString() + "!");

                if (OrderState.Delivery.equals(order.getOrderState())) {
                    Boolean result = shopOrderService.deliveryOrder(order, expressType, expressCodeStr, getCurrentUser());
                    if (!result)
                        return CodeContent.returnFailure("序号" + idStr + "订单发货失败!");

                    //将短信提醒的方式改为消息机制
                    if (result) {
                        User customer = userService.findEntityById(order.getUserId());
                        if (customer != null && customer.getPhone() != null) {
                            Messages usersMessage = new Messages();
                            usersMessage.setUserId(customer.getId());
                            usersMessage.setContent("您快递单号为" + order.getWayBillNum() + "的商品已经发货");
                            usersMessage.setIfRead(false);
                            usersMessage.setType(0);
                            usersMessage.setTitle("您购买的订单已发货");
                            usersMessage.setCreateTime(new Date());
                            messagesDao.add(usersMessage);
                        }
                    }
                } else {
                    return CodeContent.returnFailure("序号" + idStr + "订单同意发货失败!");
                }
            }
        }
        return CodeContent.returnFailure("导入成功！");
    }

    protected User getCurrentUser() {
        if (SecurityUtils.getSubject().getPrincipal() instanceof String) {
            SecurityUtils.getSubject().logout();
            return null;
        }

        Login login = (Login) SecurityUtils.getSubject().getPrincipal();
        if (login != null) {
            User user = userService.getByName(login.getName());
            if (user == null || UserState.Invalid.equals(user.getUserState()) || !user.getPassword().equals(login.getPwd())) {
                SecurityUtils.getSubject().logout();
                return null;
            } else
                return user;
        }

        return null;
    }

    /**
     *    shopOrder
     * crm 获取订单详细信息
     * ffl
     * 2017-11-12 09:12:28
     * @param token
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value ="/detail.json",produces = "application/json;charset=utf-8")
    public String getShopOrderDetail(String token,String id){
        return shopOrderService.getByShopOrderId(token, id);
    }

    /**
     * 编辑订单  1同意发货 2驳回订单 3发货
     * ffl
     * 2017-11-12 11:15:56
     * @param token
     * @param handleDetail 处理详情
     * @param shopOrderId  订单id
     * @param handleValue 4同意发货  11不同意发货
     * @param expressTypeValue  物流公司 1圆通速递 2申通快递 3百世汇通 4中通速递 5韵达快运 6邮政包裹 7天天快递 8顺丰速递 9EMS 10宅急送 11全峰快递 12邦德快递
     * @param wayBillNum  物流单号
     * @return
     */
    @ResponseBody
    @RequestMapping(value ="/edit.json",produces = "application/json;charset=utf-8")
    public String editDoShopOrder(String token, String handleDetail, String shopOrderId, String handleValue, String expressTypeValue, String wayBillNum) {
        return shopOrderService.editDoShopOrder(token, handleDetail, shopOrderId, handleValue, expressTypeValue, wayBillNum);
    }



    @RequestMapping(value="/list",produces="application/json;charset=UTF-8")
    public ModelAndView list(ModelAndView modelAndView){
        modelAndView.setViewName("/shopOrder/list");
        return modelAndView;
    }


    @RequestMapping(value="/details",produces="application/json;charset=UTF-8")
    public ModelAndView edit(ModelAndView modelAndView,String id){
        modelAndView.addObject("id",id);
        modelAndView.setViewName("/shopOrder/detail");
        return modelAndView;
    }


    /**
     *  添加商品订单  商品唯一标识码
     *  ffl
     *  2017-11-13 11:54:41
     * @param token
     * @param goodsOrderId
     * @param goodsLmie
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/addLmie.json",produces="application/json;charset=UTF-8")
    public String addGoodsLmie(String token,String goodsOrderId,String goodsLmie){
        return shopOrderService.addGoodsLmie(token, goodsOrderId, goodsLmie);
    }




    /**
     * 获取商品订单list
     * ffl
     * 2017-11-13 15:02:42
     * @param token
     * @param shopOrderCode
     * @param pageNum
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/goodsOrderList.json",produces="application/json;charset=UTF-8")
    public String goodsOrderList(String token,String shopOrderCode,String pageNum){
        return shopOrderService.goodsOrderList(token, shopOrderCode, pageNum);
    }

    /**
     * 商品订单详情
     * ffl
     * 2017-11-13 15:06:11
     * @param token
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getByGoodsOrderId.json",produces="application/json;charset=UTF-8")
    public String getByGoodsOrderId(String token,String id){
        return shopOrderService.getByGoodsOrderId(token, id);
    }


    /**
     * 订单查询用  选择店铺或仓库
     * ffl
     * 2017-11-13 16:54:08
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/shopList.json",produces="application/json;charset=UTF-8")
    public String getShopList(){
        return shopOrderService.getShopList();
    }

    /**
     * 到店自取   线下支付
     * ffl
     * 2018-01-12 15:51:58
     * @param token
     * @param password
     * @param shopOrderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/confirmShopOrder.json",produces="application/json;charset=UTF-8")
    public String confirmShopOrder(String token, String password, String shopOrderId) {
        return shopOrderService.confirmShopOrder(token, password, shopOrderId);
    }
}
